package edu.ccut.saturn.manager.bundles.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.osgi.framework.Bundle;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.core.ServiceFactory;

public class FileExist extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		String fileName = (String) parameterContext.getParameterValue(0);

		String fileExist = "false";
		String fileDirty = "false";
		
		Bundle[] bundles = ServiceFactory.getBundleService().getBundles();
		if(fileName.indexOf("_") == -1){
			fileDirty = "true";
		}
		
		if (bundles != null && "false".equals(fileDirty)) {
			for (Bundle bundle : bundles) {
				String bundleName = fileName.substring(0, fileName.indexOf("_"));
				if (bundle.getSymbolicName().equals(bundleName)){				
                   fileExist = "true";
                   break;
				}
			}                                         
		}
		
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		try {
			String sql = "select * from bundlesInfo where bundlefilename = ?";
		    preparedStatement = parameterContext.getConnection().prepareStatement(sql);
			preparedStatement.setString(1,fileName);
			
		    resultSet = preparedStatement.executeQuery();
		    
			if(resultSet.next()) {
				fileExist = "true";
			}
			
		} catch (RuntimeException e) {			
			logger.error("found exception when execute Component Node "
					+ this.getComponentFullKey(), e);
		} finally {
			if (resultSet != null) {
				resultSet.close();
			}
			if (preparedStatement != null) {
				preparedStatement.close();
			}
		}
		
		parameterContext.setParameter(1, fileExist);
		parameterContext.setParameter(2, fileDirty);
	}
}